/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pack_servlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import pack_gestionarCarrito.Carrito;
import pack_gestionarCarrito.Compra;
import pack_gestionarProducto.ActualizarBD;
import pack_gestionarProducto.ListaProducto;

/**
 *
 * @author Fernando
 */
@WebServlet(name = "ActualizarCarrito", urlPatterns = {"/ActualizarCarrito"})
public class ActualizarCarrito extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            /* TODO output your page here. You may use following sample code. */
            HttpSession AplicationSession = request.getSession(true);
            ListaProducto lista = (ListaProducto) AplicationSession.getAttribute("objListaProducto");
            if (AplicationSession.getAttribute("carro") == null) {
                AplicationSession.setAttribute("carro", new Carrito());
            }
            Carrito carro = (Carrito) AplicationSession.getAttribute("carro");
            int id = Integer.parseInt(request.getParameter("id"));
            int cantidad = Integer.parseInt(request.getParameter("cantidad"));
            System.out.println("Cantidad: "+cantidad);
            if (carro.getLista() != null) {
                int index = carro.buscarId(lista.getLista()[id].getID());
                ActualizarBD update = new ActualizarBD();
                // si index es == -2, se inserta un nuevo producto al carrito.
                // si index es diferencte de -2, el producto existe y se procede
                // a actualizar el producto.
                if (index == -2) {
                    carro.adicionarAlCarrito(new Compra(lista.getLista()[id].getID(), cantidad, (cantidad * lista.getLista()[id].getPrecio()), ((cantidad * lista.getLista()[id].getPrecio()) / 1000)));
                    update.actualizar(lista.getLista()[id].getCantidad() - cantidad, lista.getLista()[id].getID());
                } else {
                    Compra temp = carro.getLista().get(index);
                    int cant = cantidad + temp.getCantidad();
                    carro.actualizarElCarrito(index, new Compra(lista.getLista()[id].getID(), cant, (cant * lista.getLista()[id].getPrecio()), ((cant * lista.getLista()[id].getPrecio()) / 1000)));
                    update.actualizar(lista.getLista()[id].getCantidad() - cantidad, lista.getLista()[id].getID());
                }
            }
            AplicationSession.setAttribute("contadorProducto", carro.contarArticulos());
            AplicationSession.setAttribute("TotalCompra", carro.getTotal_compra());
            AplicationSession.setAttribute("carro", carro);
            System.out.println("Tamaño lista: " + carro.getLista().size());
            //System.out.println("---------------INICIO--------------------");
            //mostrar(carro.getLista());
            response.sendRedirect("index.jsp");
        } 
        finally {            
            
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void mostrar(ArrayList<Compra> lista) {
        for (Compra compra : lista) {

            System.out.println("ITEM AÑADIDO");
            System.out.println("Id_producto: " + compra.getId_producto());
            System.out.println("Cantidad: " + compra.getCantidad());
            System.out.println("Subtotal: " + compra.getSubtotal());
            System.out.println("Puntos: " + compra.getPuntos());
        }
        System.out.println("---------------FIN--------------------");
    }
}
